import {
	HTTP_SERVER_URL,
	STATUS_CODE
} from '../../config';

// 获取状态码
function getStatusText(code, type) {
  let text = '未知状态码';
  if (STATUS_CODE[type][code] !== undefined) {
    text = STATUS_CODE[type][code];
  } else if (STATUS_CODE['HTTP'][code] !== undefined) {
	  text = STATUS_CODE['HTTP'][code];
  }  else {
	  text = '未知状态码';
  }
  return text;
}
/* 本项目与后台对接的回调 */
function requestHandler(param) {
	if (!param) return {};
	try {
		// 本项目后台空串插入到非varchar类型数据库字段时会发生报错（没做实体类类型映射），故request前将空串替换为null
		let paramStr = JSON.stringify(param);
		paramStr = paramStr.replace(/""/g, 'null');
		return JSON.parse(paramStr);
	} catch (ex) {
		return param;
	}
}

function callbackHandler(res, resolve, reject, options) {
	if (res.data.code === 0) {
		resolve(res);
	} else {
		if(res.data.message){
			let message = res.data.message;
			errorHandler({
				message
			}, reject, options);
		}else{
			let message = res.data.msg;
			errorHandler({
				message
			}, reject, options);
		}
		
	}
}

function errorHandler(error, reject, options) {
	if (options.showError)  {
		uni.showToast({
			title: error.message,
			icon: 'none',
			duration: 2000
		});
	}

	// if (error.message !== '操作取消') {
	// 	reject({
	// 		message: error.message
	// 	});
	// }
}

function getToken() {
	const token = uni.getStorageSync('open').jwt || '';
	// const token = '1346985032039137281';
	if(token) {
		return token;
	} else return '';
	
}


export default new(class HttpApi {
	// get请求
	get(url, param, options = {
		showMessage: true,
		showError: true
	}) {
		param = requestHandler(param);
		// #ifdef APP-PLUS
		url = HTTP_SERVER_URL + url;
		// #endif
		// #ifdef MP-WEIXIN
		url = HTTP_SERVER_URL + url;
		// #endif
		return new Promise((resolve, reject) => {
			uni.request({
				url,
				header: {
					'token': getToken()
				},
				method: 'GET',
				data: param || {},
				success: res => {
					callbackHandler(res, resolve, reject, options);
				},
				fail: err => {
					errorHandler(err, reject, options);
				},
				complete: () => {}
			});
		});
	}

	// post请求
	post(url, param, options = {
		showMessage: true,
		showError: true
	}) {
		param = requestHandler(param);
		// #ifdef APP-PLUS
		url = HTTP_SERVER_URL + url;
		// #endif
		// #ifdef MP-WEIXIN
		url = HTTP_SERVER_URL + url;
		// #endif
		return new Promise((resolve, reject) => {
			uni.request({
				url,
				header: {
					'token': getToken()
				},
				method: 'POST',
				data: param || {},
				success: res => {
					callbackHandler(res, resolve, reject, options);
				},
				fail: err => {
					errorHandler(err, reject, options);
				},
				complete: () => {}
			});
		});
	}
})();
